<?php
declare (strict_types = 1);

namespace app\controller;

use think\Request;
use app\BaseController;
use think\facade\View;
use app\middleware\CheckLogin;
use app\model\SettingUser as UserModel;
use app\model\SettingUsergroup as UsergroupModel;

class User extends BaseController
{

    // 注册控制器中间件
    protected $middleware = [CheckLogin::class];
    
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //获取所有数据
        $sales = UserModel::select();

        for ($i=0; $i < count($sales); $i++) { 
            $group = UsergroupModel::find($sales[$i]['userAuthLevel']);
            $sales[$i]['group_name'] = $group['name'];
        }

        View::assign('sales',$sales);

        return view('index'); 
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {   
        //拉取用户组信息
        $group = UsergroupModel::order('order','asc')->select();
        View::assign('group',$group);
        //
        return view('create'); 
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = request()->param();
        $data['password'] = md5((string)$data['password']);
        $result = UserModel::create($data);//调用create方法写入数据库
        if($result == false){
            return 0;
        }else{
            return $result->id;
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    // public function read($id)
    // {
    //     //
    // }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //获取此前数据
        $data = UserModel::where('id',$id)->find();
        View::assign('data',$data);

        //拉取用户组信息
        $group = UsergroupModel::order('order','asc')->select();
        View::assign('group',$group);

        return view('edit'); 
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $data = request()->param();
        if(!empty($data['password'])){
            $data['password'] = md5((string)$data['password']);
        }else{
            unset($data['password']);
        }
        $result = UserModel::update($data);//调用create方法写入数据库
        if($result == false){
            return 0;
        }else{
            return $result->id;
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //删除
        $user = UserModel::find($id);//删除id号
        $result = $user->delete();//确认删除结果，返回布尔值
        if($result){
            return "ok";//成功则返回OK
        }else{
            return "false";//失败则返回false
        }
    }
}
